<template>
  <div class="guid-generator-tool">
    <div class="tool-header">
      <h1>GUID生成工具</h1>
      <p>快速生成全局唯一标识符（GUID/UUID）</p>
    </div>

    <div class="tool-container">
      <el-row :gutter="20">
        <!-- 配置区域 -->
        <el-col :span="12">
          <div class="config-section">
            <div class="section-header">
              <h3>生成配置</h3>
            </div>
            
            <div class="config-options">
              <div class="option-group">
                <label>生成数量：</label>
                <el-input-number
                  v-model="guidCount"
                  :min="1"
                  :max="100"
                  controls-position="right"
                />
              </div>
              
              <div class="option-group">
                <label>格式选择：</label>
                <el-radio-group v-model="guidFormat">
                  <el-radio label="uppercase">大写格式</el-radio>
                  <el-radio label="lowercase">小写格式</el-radio>
                  <el-radio label="braces">带大括号</el-radio>
                  <el-radio label="parentheses">带小括号</el-radio>
                </el-radio-group>
              </div>
              
              <div class="option-group">
                <label>分隔符：</label>
                <el-radio-group v-model="separator">
                  <el-radio label="hyphens">连字符 (-)</el-radio>
                  <el-radio label="none">无分隔符</el-radio>
                </el-radio-group>
              </div>
            </div>
            
            <div class="generate-actions">
              <el-button 
                type="primary" 
                @click="generateGuids"
                :loading="isGenerating"
                size="large"
              >
                <el-icon><Refresh /></el-icon>
                生成GUID
              </el-button>
              <el-button @click="clearAll" size="large">清空</el-button>
            </div>
          </div>
        </el-col>

        <!-- 结果区域 -->
        <el-col :span="12">
          <div class="result-section">
            <div class="section-header">
              <h3>生成的GUID</h3>
              <div class="actions">
                <el-button @click="copyAllGuids" size="small" :disabled="!guids.length">复制全部</el-button>
                <el-button @click="clearGuids" size="small">清空</el-button>
              </div>
            </div>
            
            <div class="guids-container">
              <div 
                v-for="(guid, index) in guids" 
                :key="index"
                class="guid-item"
              >
                <div class="guid-info">
                  <span class="guid-number">{{ index + 1 }}</span>
                  <span class="guid-type">{{ getGuidType(guid) }}</span>
                </div>
                <div class="guid-content">
                  <el-input
                    :model-value="guid"
                    readonly
                    class="guid-input"
                  />
                  <el-button @click="copyGuid(guid)" size="small">复制</el-button>
                </div>
              </div>
            </div>
            
            <div class="guid-stats" v-if="guids.length">
              <el-tag type="info" size="small">
                已生成 {{ guids.length }} 个GUID
              </el-tag>
              <el-tag type="success" size="small">
                格式: {{ getFormatDescription() }}
              </el-tag>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- GUID格式说明 -->
      <div class="format-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>GUID格式说明</span>
            </div>
          </template>
          
          <div class="format-content">
            <div class="format-examples">
              <div class="format-item">
                <h4>标准格式（大写）</h4>
                <code>550E8400-E29B-41D4-A716-446655440000</code>
              </div>
              <div class="format-item">
                <h4>标准格式（小写）</h4>
                <code>550e8400-e29b-41d4-a716-446655440000</code>
              </div>
              <div class="format-item">
                <h4>带大括号</h4>
                <code>{550E8400-E29B-41D4-A716-446655440000}</code>
              </div>
              <div class="format-item">
                <h4>带小括号</h4>
                <code>(550E8400-E29B-41D4-A716-446655440000)</code>
              </div>
              <div class="format-item">
                <h4>无分隔符</h4>
                <code>550E8400E29B41D4A716446655440000</code>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 使用说明 -->
      <div class="tool-info">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>使用说明</span>
            </div>
          </template>
          
          <div class="info-content">
            <h4>什么是GUID？</h4>
            <p>GUID（Globally Unique Identifier）全局唯一标识符，也称为UUID（Universally Unique Identifier），是一个128位的数字，用于在计算机系统中唯一标识信息。</p>
            
            <h4>GUID的特点：</h4>
            <ul>
              <li>全局唯一：在时间和空间上都是唯一的</li>
              <li>随机性：基于随机数生成</li>
              <li>标准化：遵循RFC 4122标准</li>
              <li>跨平台：可在不同系统间使用</li>
            </ul>
            
            <h4>使用场景：</h4>
            <ul>
              <li>数据库主键</li>
              <li>分布式系统标识</li>
              <li>文件唯一标识</li>
              <li>API接口标识</li>
              <li>日志追踪</li>
            </ul>
            
            <h4>版本说明：</h4>
            <div class="version-info">
              <p>本工具生成的是<strong>版本4</strong>的GUID，基于随机数生成，具有最高的唯一性保证。</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'

const guidCount = ref(5)
const guidFormat = ref('uppercase')
const separator = ref('hyphens')
const guids = ref([])
const isGenerating = ref(false)

const generateGuids = async () => {
  isGenerating.value = true
  try {
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const newGuids = []
    for (let i = 0; i < guidCount.value; i++) {
      const guid = generateGuid()
      newGuids.push(guid)
    }
    
    guids.value = newGuids
    ElMessage.success(`已生成 ${guidCount.value} 个GUID`)
  } catch (error) {
    ElMessage.error('生成失败：' + error.message)
  } finally {
    isGenerating.value = false
  }
}

const generateGuid = () => {
  // 生成版本4的GUID
  const hex = '0123456789abcdef'
  let guid = ''
  
  // 生成32个十六进制字符
  for (let i = 0; i < 32; i++) {
    guid += hex[Math.floor(Math.random() * 16)]
  }
  
  // 设置版本4标识
  guid = guid.substring(0, 12) + '4' + guid.substring(13, 16)
  
  // 设置变体标识
  const variantChar = hex[Math.floor(Math.random() * 4) + 8] // 8, 9, a, b
  guid = guid.substring(0, 16) + variantChar + guid.substring(17)
  
  // 根据格式要求处理
  let formattedGuid = guid
  
  if (separator.value === 'hyphens') {
    formattedGuid = [
      guid.substring(0, 8),
      guid.substring(8, 12),
      guid.substring(12, 16),
      guid.substring(16, 20),
      guid.substring(20, 32)
    ].join('-')
  }
  
  if (guidFormat.value === 'uppercase') {
    formattedGuid = formattedGuid.toUpperCase()
  } else if (guidFormat.value === 'lowercase') {
    formattedGuid = formattedGuid.toLowerCase()
  } else if (guidFormat.value === 'braces') {
    formattedGuid = '{' + formattedGuid + '}'
  } else if (guidFormat.value === 'parentheses') {
    formattedGuid = '(' + formattedGuid + ')'
  }
  
  return formattedGuid
}

const getGuidType = (guid) => {
  if (guid.includes('{') && guid.includes('}')) return '大括号格式'
  if (guid.includes('(') && guid.includes(')')) return '小括号格式'
  if (guid.includes('-')) return '标准格式'
  return '无分隔符'
}

const getFormatDescription = () => {
  const formatMap = {
    'uppercase': '大写',
    'lowercase': '小写',
    'braces': '大括号',
    'parentheses': '小括号'
  }
  const separatorMap = {
    'hyphens': '连字符',
    'none': '无分隔符'
  }
  return `${formatMap[guidFormat.value]} + ${separatorMap[separator.value]}`
}

const copyGuid = async (guid) => {
  try {
    await navigator.clipboard.writeText(guid)
    ElMessage.success('GUID已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = guid
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('GUID已复制到剪贴板')
  }
}

const copyAllGuids = async () => {
  if (guids.value.length === 0) {
    ElMessage.warning('没有可复制的GUID')
    return
  }
  
  const allGuids = guids.value.join('\n')
  try {
    await navigator.clipboard.writeText(allGuids)
    ElMessage.success('所有GUID已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const clearGuids = () => {
  guids.value = []
  ElMessage.info('已清空GUID列表')
}

const clearAll = () => {
  guids.value = []
  guidCount.value = 5
  guidFormat.value = 'uppercase'
  separator.value = 'hyphens'
  ElMessage.info('已重置所有配置')
}
</script>

<style scoped>
.guid-generator-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.tool-header {
  text-align: center;
  margin-bottom: 40px;
}

.tool-header h1 {
  font-size: 2.5rem;
  color: #333;
  margin-bottom: 10px;
}

.tool-header p {
  color: #666;
  font-size: 1.1rem;
}

.tool-container {
  margin-bottom: 40px;
}

.config-section,
.result-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #f0f0f0;
  height: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  color: #333;
  margin: 0;
  font-size: 1.3rem;
}

.actions {
  display: flex;
  gap: 8px;
}

.config-options {
  margin-bottom: 30px;
}

.option-group {
  margin-bottom: 20px;
}

.option-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.generate-actions {
  display: flex;
  gap: 12px;
  margin-top: 30px;
}

.guids-container {
  max-height: 400px;
  overflow-y: auto;
  margin-bottom: 20px;
}

.guid-item {
  margin-bottom: 15px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.guid-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.guid-number {
  font-weight: bold;
  color: #667eea;
}

.guid-type {
  padding: 2px 8px;
  background: #d1ecf1;
  color: #0c5460;
  border-radius: 4px;
  font-size: 0.8rem;
  font-weight: bold;
}

.guid-content {
  display: flex;
  gap: 8px;
  align-items: center;
}

.guid-input {
  flex: 1;
}

.guid-input :deep(.el-input__inner) {
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
}

.guid-stats {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.format-info,
.tool-info {
  margin-top: 40px;
}

.card-header {
  font-weight: bold;
  color: #333;
}

.format-examples {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.format-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.format-item h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 1rem;
}

.format-item code {
  display: block;
  font-family: 'Courier New', monospace;
  font-size: 0.9rem;
  color: #667eea;
  background: white;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #dee2e6;
  word-break: break-all;
}

.info-content h4 {
  color: #333;
  margin: 20px 0 10px 0;
  font-size: 1.1rem;
}

.info-content p {
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.info-content ul {
  color: #666;
  padding-left: 20px;
  margin-bottom: 15px;
}

.info-content li {
  margin-bottom: 5px;
}

.version-info {
  background: #d1ecf1;
  padding: 15px;
  border-radius: 8px;
  border-left: 4px solid #17a2b8;
  margin: 15px 0;
}

.version-info p {
  margin: 0;
  color: #0c5460;
}

@media (max-width: 768px) {
  .tool-header h1 {
    font-size: 2rem;
  }
  
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .generate-actions {
    flex-direction: column;
  }
  
  .guid-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .format-examples {
    grid-template-columns: 1fr;
  }
}
</style>
